<template>
  <div class="container-full">
    <div class="toolbar">
      <div class="btn-group" role="group" aria-label="Basic example">
        <button type="button" class="btn" @click="selectCustomer()">
          <i class="iconfont icon-plus"></i> 新建
        </button>
      </div>
    </div>
    <form class="form-inline filter-pane" v-on:submit.prevent="onSearch()">
      <div class="form-group" style="padding-right:10px">
        <input type="text" class="form-control" placeholder="关键词" v-model="keyword">
      </div>
      <div class="form-group" style="padding-right:10px">
        <select class="form-control" v-model="status">
          <option value="0">待处理</option>
          <option value="1">已处理</option>
        </select>
      </div>
      <button type="button" class="btn btn-primary" @click="onSearch()">查询</button>
    </form>
    <div class="grid-host">
      <div class="grid" id="orderGrid">
        <div class="grid-body">
          <table border="0" cellpadding="0" cellspacing="0">
            <thead>
              <tr class="grid-hidden-header">
                <th width="238px">订单号</th>
                <th :key="col.name" v-for="col in columns" :width="col.width">{{col.text}}</th>
              </tr>
            </thead>
            <tbody>
              <tr :key="entry.id" v-for="(entry, index) in items">
                <!-- <td>
                  <img
                    :src="'https://data.ysmove.com/' + entry.default_image"
                    class="img-responsitive"
                    style="max-height:48px"
                  >
                </td>-->
                <td style="position:relative;padding-right:36px">
                  <a href="javascript:;" @click="onItemClick(entry)">{{entry.order_sn}}</a>
                  <div class="btn-group btn-group-sm grid-actions">
                    <button
                      v-if="entry.status != '0' && entry.status != '40'"
                      class="btn btn-sm btn-cancel"
                      @click="handleCancelEvent(index)"
                    >
                      <i class="iconfont icon-poweroff"></i> 取消
                    </button>
                    <button
                      v-if="entry.status == '0'"
                      class="btn btn-sm btn-remove"
                      @click="handleRemoveEvent(index)"
                    >
                      <i class="iconfont icon-shanchu"></i> 删除
                    </button>
                    <button
                      v-if="entry.status > 0 && entry.status < 20"
                      class="btn btn-sm btn-confirm"
                      @click="handleConfirmEvent(index)"
                    >
                      <i class="iconfont icon-duigou"></i> 确认
                    </button>
                  </div>
                </td>
                <td
                  :key="col.name"
                  v-for="col in columns"
                  class="cell-content"
                  style="position:relative"
                >{{entry[col.name]}}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="grid-footer">
          <div v-if="pageable != null" class="footer-content">
            <div class="status">共找到记录: {{pageable.totalCount}}</div>
            <pagination :pageable="pageable"/>
          </div>
        </div>
      </div>
    </div>
    <div id="customer-dialog" class="modal" tabindex="-1" role="dialog">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">选择客户</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <customer-picker :selectedItems="selectedCustomers"/>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" v-on:click="completeSelectCustomer()">确定</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          </div>
        </div>
      </div>
    </div>
    <div id="confirm-dialog" class="modal" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">确认订单</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form role="form">
              <div class="form-group">
                <label class="control-label">实收金额</label>
                <input type="number" class="form-control" v-model="orderAmount"/>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" v-on:click="submitConfirmOrder()">确定</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CustomerPicker from "./CustomerPicker";
import Pagination from "@/components/Pagination"

export default {
  name: "OrderList",
  components: { CustomerPicker, Pagination },
  data() {
    return {
      keyword: "",
      status: "0",
      currentCustomer: null,
      selectedCustomers: [],
      keyName: "order_id",
      orderAmount: 0,
      activeOrderIndex: -1,
      items: [],
      pageable: null,
      columns: [
        { text: "状态", name: "statusName", width: "60px" },
        { text: "客户", name: "buyer_name", width: "180px" },
        { text: "电话", name: "buyer_mobile", width: "120px" },
        { text: "金额", name: "goods_amount", width: "75px" },
        { text: "数量", name: "goods_count", width: "50px" },
        { text: "支付方式", name: "payment_name", width: "150px" },
        { text: "建立时间", name: "created", width: "180px" },
        { text: "完成时间", name: "completed", width: "180px" }
      ]
    };
  },
  methods: {
    onSearch() {
      this.goto(1);
    },
    completeSelectCustomer() {
      var items = this.selectedCustomers;
      if (items.length > 0) {
        $("#customer-dialog").modal("hide");
        this.currentCustomer = items[0];
        console.log("selected customer: ", this.currentCustomer);
        localStorage.setItem('customer', JSON.stringify(this.currentCustomer));

        this.$router.push({
          path: "/order/create",
          query: {
            customerId: this.currentCustomer.user_id
          }
        });
      } else {
        alert("请选择客户");
      }
    },
    selectCustomer() {
      $("#customer-dialog").modal("show");
    },
    handleConfirmEvent(index) {
      this.orderAmount = 0;
      this.activeOrderIndex = index;

      $("#confirm-dialog").modal("show");
    },
    submitConfirmOrder() {
      if(!confirm('确定要确认该订单?'))
        return;
      
      var item = this.items[this.activeOrderIndex];
      this.$order.confirm(item.order_id, this.orderAmount).then(rsp => {
        var data = rsp.data;
        console.log(data);
        if(data.success) {
          $("#confirm-dialog").modal("hide");
          this.goto(this.pageable.currentPage);
        } else {
          alert('失败');
        }
      });
    },
    handleCancelEvent(index) {
      if (confirm("确定要取消该订单?")) {
        var item = this.items[index];
        var self = this;
        var currentPage = this.pageable.currentPage;

        this.$order.cancel(item.order_id).then(rsp => {
          var data = rsp.data;
          if(data.success) {
            self.$delete(self.items, index);
            self.onPage(currentPage);
          } else {
            alert('操作失败');
          }
        });
      }
    },
    handleRemoveEvent(index) {
      if (confirm("确定要删除该订单?")) {
        var item = this.items[index];
        var self = this;

        this.$order.remove(item.order_id).then(rsp => {
          var data = rsp.data;
          if(data.success) {
            self.$delete(self.items, index);
          } else {
            alert('操作失败');
            //console.log('delete', rsp);
          }
        });     
      }
    },
    onItemClick(item) {
      var orderId = item.order_id;
      const page = this.pageable ? this.pageable.currentPage : 1;

      this.$router.push({
        path: "/order/details",
        query: {
          id: orderId
        }
      });
    },
    goto(page) {
      this.$user
        .getOrdersForShipping(this.keyword, this.status, page)
        .then(r => {
          const result = r.data;
          if (result.success) {
            var items = result.data.items;

            //格式化
            for (var i = 0; i < items.length; i++) {
              var item = items[i];

              item.created = this.$helper.toDate(item.add_time);
              if (item.status === "0" || item.status === "40")
                item.completed = this.$helper.toDate(item.finished_time);

              item.statusName = this.$order.getStatusName(item.status);
            }

            this.items = items;
            this.pageable = result.data._meta;
            if (this.pageable) {
              this.pageable.goto = this.goto;

              //记住当前页码
              //.state["OrderList.Page"] = page;
            }
          }
        });
    }
  },
  mounted() {
    $("#orderGrid").grid();

    const query = this.$router.currentRoute.query;
    var page = 1;
    if (query.page) page = query.page;
    else {
      //var storedPage = store.state["OrderList.Page"];
      //if (storedPage) page = storedPage;
    }

    this.goto(page);
  }
};
</script>
<style lang="scss">
.container-full {
  display: block;
  position: relative;
  height: 100%;
  width: 100%;
  padding-top: 90px;
}

.filter-pane {
  position: absolute;
  top: 40px;
  padding: 15px;
}

.grid-host {
  height: 100%;
  width: 100%;
  padding: 15px;
  position: relative;
}

@import "@/assets/app.scss";

.grid-col-check {
  width: 45px;
}

.grid .grid-actions {
  position: absolute;
  right: 2px;
  top: 1px;
}

.grid .grid-actions .btn {
  border:none;
}

.btn-cancel {
  color:rgb(255, 174, 0);
}

.btn-remove {
  color: red;
}

.btn-confirm {
  color: green;
  font-weight: 700;
}

.grid-col-check .custom-control,
.grid-cell-check .custom-control {
  padding-left: 2rem;
}

.footer-content {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
  padding-left: 15px;
  padding-right: 15px;
}

.status {
  flex: 0 120px;
  height: 100%;
  vertical-align: middle;
  line-height: 38px;
}

// .pager {
//   flex: 1;
//   height: 100%;
//   text-align: right;
//   vertical-align: middle;
//   padding-right: 15px;
//   line-height: 38px;
// }

.pagination-container {
  flex: 1;
  // align-items: right;
  // height: 100%;
  padding-top: 3px;
}

.pagination-container > .pagination {
  height: 100%;
  margin-bottom: 0;
}

.pull-right {
  float: right;
}

.grid-footer {
  position: absolute;
  height: 38px;
  bottom: 0px;
  width: 100%;
  border-top: 1px solid $borderColor;
}
</style>

